package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import org.springframework.security.core.userdetails.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    //注入UserService
    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据框架给的用户名查询用户信息 注意 这个user 是对应user表生成的pojo类
        System.out.println("username = ===========================================" + username);
        com.itheima.pojo.User user = userService.findByUsername(username);

        //如果用户不存在 说明输入的用户名有问题 或者用户未注册
        if (user == null){
            //返回空，页面自动跳回登录页面
            return null;
        }

        //创建一个权限集合，用于存储查询到的用户角色和权限
        List<GrantedAuthority> list = new ArrayList<>();
        //用户所有的角色
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //将用户的角色添加进去
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //授予用户权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        User userDetails = new User(username, user.getPassword(), list);

        return userDetails;
    }
}
